import 'package:efood_multivendor/controller/order_controller.dart';
import 'package:efood_multivendor/controller/splash_controller.dart';
import 'package:efood_multivendor/data/api/api_checker.dart';
import 'package:efood_multivendor/data/model/body/review_body.dart';
import 'package:efood_multivendor/data/model/response/cart_model.dart';
import 'package:efood_multivendor/data/model/response/order_details_model.dart';
import 'package:efood_multivendor/data/model/response/order_review_model.dart';
import 'package:efood_multivendor/data/model/response/product_model.dart';
import 'package:efood_multivendor/data/model/response/response_model.dart';
import 'package:efood_multivendor/data/repository/product_repo.dart';
import 'package:efood_multivendor/helper/size_config.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/view/base/custom_snackbar.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class ProductController extends GetxController implements GetxService {
  final ProductRepo productRepo;

  ProductController({required this.productRepo});

  List<Product>? _popularProductList;
  List<Product>? _reviewedProductList;
  bool _isLoading = false;
  List<int>? _variationIndex;
  int _quantity = 1;
  Map<int, List<bool>> _addOnActiveList = {};
  List<int> _addOnQtyList = [];
  String _popularType = 'all';
  String _reviewedType = 'all';
  static List<String> _productTypeList = ['all', 'veg', 'non_veg'];
  List<int>? _addOnId;
  UnreviewedOrdersResponse? _unreviewedOrdersResponse;

  List<Product>? get popularProductList => _popularProductList;

  List<Product>? get reviewedProductList => _reviewedProductList;

  bool get isLoading => _isLoading;

  List<int>? get variationIndex => _variationIndex;

  int get quantity => _quantity;

  Map<int, List<bool>> get addOnActiveList => _addOnActiveList;

  List<int>? get addOnId => _addOnId;

  List<int> get addOnQtyList => _addOnQtyList;

  String get popularType => _popularType;

  String get reviewType => _reviewedType;

  List<String> get productTypeList => _productTypeList;

  UnreviewedOrdersResponse? get unreviewedOrdersResponse =>
      _unreviewedOrdersResponse;

  Future<Product?> getProductDetails(Product product) async {
    Product? _product;
    Response response = await productRepo.getProductDetail(product.id!);
    if (response.statusCode == 200) {
      _product = Product.fromJson(response.body);
    } else {
      Get.find<OrderController>().stopProductLoader();
      showCustomSnackBar('not_found'.tr);
    }

    update();

    return _product;
  }

  Future<void> getPopularProductList(
      bool reload, String type, bool notify) async {
    _popularType = type;
    if (reload) {
      _popularProductList = null;
    }
    if (notify) {
      update();
    }
    if (_popularProductList == null || reload) {
      Response response = await productRepo.getPopularProductList(type);
      if (response.statusCode == 200) {
        _popularProductList = [];
        _popularProductList!
            .addAll(ProductModel.fromJson(response.body).products!);
        _isLoading = false;
      } else {
        ApiChecker.checkApi(response);
      }
      update();
    }
  }

  Future<void> getReviewedProductList(
      bool reload, String type, bool notify) async {
    _reviewedType = type;
    if (reload) {
      _reviewedProductList = null;
    }
    if (notify) {
      update();
    }
    if (_reviewedProductList == null || reload) {
      Response response = await productRepo.getReviewedProductList(type);
      if (response.statusCode == 200) {
        _reviewedProductList = [];
        _reviewedProductList!
            .addAll(ProductModel.fromJson(response.body).products!);
        _isLoading = false;
      } else {
        ApiChecker.checkApi(response);
      }
      update();
    }
  }

  void showBottomLoader() {
    _isLoading = true;
    update();
  }

  void initData(Product? product, CartModel? cart) {
    if (product?.choiceOptions == null) {
      product?.choiceOptions = [];
    }
    if (cart != null) {
      _quantity = cart.quantity;
      List<String> _variationTypes = [];
      if (cart.variation?.length != null &&
          cart.variation!.length > 0 &&
          cart.variation?[0].type != null) {
        _variationTypes.addAll(cart.variation![0].type!.split('-'));
      }
      int _varIndex = 0;
      product?.choiceOptions!.forEach((choiceOption) {
        for (int index = 0; index < choiceOption.options!.length; index++) {
          if (choiceOption.options![index].trim().replaceAll(' ', '') ==
              _variationTypes[_varIndex].trim()) {
            _variationIndex?.add(index);
            break;
          }
        }
        _varIndex++;
      });
    } else {
      _quantity = 1;
      product?.choiceOptions!.forEach((element) => _variationIndex?.add(0));
      product?.addOns!.forEach((addOn) {
        if (_addOnActiveList.containsKey(product.id)) {
          _addOnActiveList[product.id]?.add(false);
        } else {
          _addOnActiveList.addEntries((<int, List<bool>>{
            product.id!: [false]
          }).entries);
        }

        _addOnQtyList.add(1);
      });
    }
  }

  void setAddOnQuantity(bool isIncrement, int index) {
    if (isIncrement) {
      _addOnQtyList[index] = _addOnQtyList[index] + 1;
    } else {
      _addOnQtyList[index] = _addOnQtyList[index] - 1;
    }
    update();
  }

  void setQuantity(bool isIncrement) {
    if (isIncrement) {
      if (_quantity >=
          Get.find<SplashController>().configModel!.limitPerItemValue!) {
        AlertDialog alert3 = AlertDialog(
          scrollable: true,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(Dimensions.RADIUS_EXTRA_LARGE),
          ),
          title: Center(
              child: Column(
            children: [
              Icon(
                Icons.info,
                size: 50,
                color: Colors.deepOrange,
              )
            ],
          )),
          content: Container(
              width: 60.w,
              height: 7.5.h,
              margin: EdgeInsets.only(bottom: 15),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius:
                    BorderRadius.circular(Dimensions.PADDING_SIZE_EXTRA_LARGE),
              ),
              child: Center(
                  child: Wrap(
                children: [
                  Text(
                      '${Get.find<SplashController>().configModel!.limitPerItemTip}'
                          .tr,
                      style: TextStyle(fontSize: Dimensions.fontSizeLarge),
                      textAlign: TextAlign.center,
                      softWrap: true,
                      maxLines: 4),
                ],
              ))),
        );
        Get.dialog(alert3, barrierDismissible: true);
      } else {
        _quantity = _quantity + 1;
      }
    } else {
      _quantity = _quantity - 1;
    }
    update();
  }

  void setCartVariationIndex(int index, int i) {
    _variationIndex![index] = i;
    update();
  }

  void addAddOn(bool isAdd, int index, int id) {
    _addOnActiveList[id]![index] = isAdd;
    update();
  }

  void clearAddOn() {
    _addOnActiveList = {};
    _addOnId = [];
    _addOnQtyList = [];
    update();
  }

  void setAddOnId(int id) {}

  List<int> _ratingList = [];
  List<String> _reviewList = [];
  List<bool> _loadingList = [];
  List<bool> _submitList = [];
  bool? _submitDelivList;
  int _deliveryManRating = 0;

  List<int> get ratingList => _ratingList;

  List<String> get reviewList => _reviewList;

  List<bool> get loadingList => _loadingList;

  List<bool> get submitList => _submitList;

  bool? get submitDelivList => _submitDelivList;

  int get deliveryManRating => _deliveryManRating;

  void initRatingData(List<Details> orderDetailsList) {
    _ratingList = [];
    _reviewList = [];
    _loadingList = [];
    _submitList = [];
    _submitDelivList = false;
    _deliveryManRating = 0;
    orderDetailsList.forEach((orderDetails) {
      _ratingList.add(0);
      _reviewList.add('');
      _loadingList.add(false);
      _submitList.add(false);
    });
  }

  void setRating(int index, int rate) {
    _ratingList[index] = rate;
    update();
  }

  void setReview(int index, String review) {
    _reviewList[index] = review;
  }

  void setDeliveryManRating(int rate) {
    _deliveryManRating = rate;
    update();
  }

  Future<ResponseModel> submitReview(int index, ReviewBody reviewBody) async {
    _loadingList[index] = true;
    update();

    Response response = await productRepo.submitReview(reviewBody);
    ResponseModel responseModel;
    if (response.statusCode == 200) {
      _submitList[index] = true;
      responseModel = ResponseModel(true, 'Review submitted successfully');
      update();
    } else {
      responseModel = ResponseModel(false, response.statusText);
    }
    _loadingList[index] = false;
    update();
    return responseModel;
  }

  Future<ResponseModel> submitDeliveryManReview(ReviewBody reviewBody) async {
    _isLoading = true;
    update();
    Response response = await productRepo.submitDeliveryManReview(reviewBody);
    ResponseModel responseModel;
    if (response.statusCode == 200) {
      _submitDelivList = true;
      _deliveryManRating = 0;
      responseModel = ResponseModel(true, 'Review submitted successfully');
      update();
    } else {
      responseModel = ResponseModel(false, response.statusText);
    }
    _isLoading = false;
    update();
    return responseModel;
  }

  Future<ResponseModel> cancelDeliveryManReviewPopup(
      DelvieryManCancelPopupBody reviewBody) async {
    _isLoading = true;
    update();
    Response response =
        await productRepo.cancelDeliveryManReviewPopup(reviewBody);
    ResponseModel responseModel;
    if (response.statusCode == 200) {
      _submitDelivList = true;
      _deliveryManRating = 0;
      responseModel = ResponseModel(true, 'Review submitted successfully');
      update();
    } else {
      responseModel = ResponseModel(false, response.statusText);
    }
    _isLoading = false;
    update();
    return responseModel;
  }

  Future<bool> getUnreviewedOrdersData() async {
    _isLoading = true;
    update();
    Response response = await productRepo.getUnreviewedOrdersData(1, 10);
    bool _isSuccess = false;
    if (response.statusCode == 200) {
      _unreviewedOrdersResponse =
          UnreviewedOrdersResponse.fromJson(response.body);
      _isSuccess = true;
    } else {
      ApiChecker.checkApi(response);
      print(response.toString());

      _isSuccess = false;
    }
    _isLoading = false;
    update();
    return _isSuccess;
  }

  setUnreviewedOrderdataToNull() {
    _unreviewedOrdersResponse = null;
    update();
  }
}
